<template>
  <div>
    <!--  流水明细  -->
    <div class="cost-details">
      <div class="details-header">
        <div style="margin-top: 10px">
          <span style="margin: 0 10px">流水明细</span>
          <el-date-picker
            v-model="value1"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="mini"
            style="margin-right: 10px"
          />
          <el-input
            v-model="pitemtype"
            placeholder="请输入流水名目"
            size="mini"
            style="width: 160px; margin-right: 10px"
          />
          <el-button size="mini" type="primary" @click="waterList">搜索</el-button>
          <el-button size="mini" type="primary" @click="newFlowing">
            新增流水
          </el-button>
        </div>
        <div class="details-lef" style="margin-top: 1vh">
          <jc-table
            :table-height="'420px'"
            :table-data="tableData1"
            :table-header="tableHeader1"
            show-summary
            :get-summaries="getSummaries"
          >
            <el-table-column type="index" :label="$t('shop.numIndex')" width="50px" align="center" />
            <template v-slot:btnSlot="col">
              <el-button-group>
                <el-button type="warning" size="mini" @click="newFlowing(col.scope.row)">{{ $t('btn.edit') }}</el-button>
                <el-button type="danger" size="mini" @click="waterDel(col.scope.row, 2)">删除</el-button>
              </el-button-group>
            </template>
          </jc-table>
          <div style="margin-top: 5px;">
            <jc-pagination
              :total="total"
              :page.sync="pageNum"
              :limit.sync="pageSize"
              @pagination="waterList"
            />
          </div>
        </div>
      </div>
      <div class="details">
        <div class="pie">
          <pie ref="pie" />
        </div>
      </div>
    </div>
    <!--  新增流水  -->
    <el-dialog
      :title="title"
      :visible.sync="flowingVisible"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form :model="flowingWater" size="mini" label-width="80px">
        <el-form-item label="流水日期" prop="date">
          <el-date-picker
            v-model="flowingWater.pdate"
            size="mini"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('market.checkDate')"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item label="权益人" prop="prightser">
          <el-autocomplete
            v-model.trim="flowingWater.prightser"
            popper-class="my-autocomplete"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            style="width: 100%"
            @select="handleSelect"
          >
            <i
              slot="suffix"
              class="el-icon-edit el-input__icon"
            />
            <template slot-scope="{ item }">
              <div class="name">{{ item }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="金额" prop="pamount">
          <el-input-number v-model="flowingWater.pamount" controls-position="right" style="width: 150px" />
        </el-form-item>
        <el-form-item label="流水名目" prop="pitemtypeid">
          <el-cascader
            v-model="flowingWater.pitemtypeid"
            :options="options"
            style="width: 100%"
            :props="{ expandTrigger: 'click' }"
          />
        </el-form-item>
        <el-form-item label="流水明细" prop="pnote">
          <el-input v-model.trim="flowingWater.pnote" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="waterSubmit">{{ $t('btn.save') }}</el-button>
          <el-button @click="flowingVisible = false">{{ $t('btn.cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {
    pie: () => import('@/views/homePageNew/manageHome/component/pie')
  },
  data() {
    return {
      title: '',
      value1: [],
      pitemtype: '',
      total: 0,
      pageNum: 1,
      pageSize: 200,
      flowingVisible: false,
      loading: false,
      tableData1: [],
      tableHeader1: [
        { label: '科目日期', prop: 'pdate', width: '100px' },
        { label: '科目类型', prop: 'pItemtypename' },
        { label: '科目名目', prop: 'pItemtype' },
        { label: '费用部门', prop: 'prightser', width: '100px' },
        { label: this.$t('market.billamount'), prop: 'pamount', width: '100px' },
        { label: '科目说明', prop: 'pnote' }
        // { label: '操作', type: 'btn', width: '150' }
      ],
      options: [],
      restaurants: [],
      flowingWater: {},
      pickerOptions: {
        // 当前日期之后禁止选择
        // disabledDate(time) {
        //   return time.getTime() > Date.now();
        // }
      }
    }
  },
  created() {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 60)
    this.value1 = [start, end]
    this.waterList() // 流水列表
  },
  methods: {
    // 流水列表
    waterList() {
      const DATA = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        pitemtype: this.pitemtype,
        sd: this.value1?.[0],
        ed: this.value1?.[1]
      }
      queryWaterList(DATA).then(res => {
        if (res.code === 0) {
          this.tableData1 = res.data.array
          this.total = res.data.total
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    },
    // 流水名目
    itemType() {
      queryItemtypeList({}).then(res => {
        if (res.code === 0) {
          this.options = res.data
        }
      })
    },
    // 新增流水
    newFlowing(item) {
      this.loading = false
      item.pid ? this.title = '修改流水' : this.title = '新增流水'
      this.restaurants = window.localStorage.getItem('restaurants')?.split(',') || []
      this.options.length === 0 && this.itemType()
      this.flowingVisible = true
      this.flowingWater = item.pid ? {
        ...item,
        pitemtypeid: item.pid ? item.pitemtypeid?.split(',') : []
      } : {
        pdate: new Date().toLocaleDateString().split('/').join('-'),
        prightser: '',
        pamount: '',
        pnote: '',
        pitemtypeid: ''
      }
      // 字符串数组 改为 数字数组
      if (item.pid) {
        this.flowingWater.pitemtypeid = this.flowingWater.pitemtypeid.map(Number)
      }
    },
    // 新增流水
    waterSubmit() {
      this.loading = true
      // 权益人缓存
      this.restaurants.push(this.flowingWater.prightser)
      window.localStorage.setItem('restaurants', Array.from(new Set(this.restaurants)))
      // 判断书否数组
      const arr = Array.isArray(this.flowingWater.pitemtypeid)
      // 拼接字符串
      this.flowingWater.pitemtypeid = arr ? this.flowingWater.pitemtypeid.join(',') : this.flowingWater.pitemtypeid
      const api = this.flowingWater.pid ? updateWateritems : insertWateritems
      api({ ...this.flowingWater }).then(res => {
        if (res.code === 0) {
          this.loading = false
          this.flowingVisible = false
          // 流水分析
          this.$refs.pie.pieWaterData()
          this.waterList()
        } else {
          this.loading = false
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
      this.loading = false
    },
    // 删除流水
    waterDel(item) {
      const pid = item.pid
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWateritems({ pid }).then(res => {
          if (res.code === 0) {
            this.waterList()
            // 流水分析
            this.$refs.pie.pieWaterData()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        })
      })
    },
    // 权益人缓存
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    }, // 权益人
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 选择权益人
    handleSelect(item) {
      this.flowingWater.prightser = item
    },
    // 合计行
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index === 6) {
          sums[index] = ''
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        }
      })
      return sums
    }
  }
}
</script>

<style scoped lang="scss">
.cost-details {
  padding: 0 5px 5px;
  margin-top: 10px;
  background-color: white;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  .details-header {
    width: 50%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;

    .details-lef {
      width: 100%;
    }
  }
  .details {
    width: 49%;
    .pie {
      width: 100%;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      color: red;
    }
  }
}
</style>

